# -*- coding: utf-8 -*-
from datetime import datetime
from sqlalchemy import Column, BigInteger, String, Integer, Boolean, DateTime, ForeignKey, UniqueConstraint
from sqlalchemy.orm import relationship

from db.base import Base
from db.models.base import BaseDatabaseModel


class MaterialTypeDict(BaseDatabaseModel, Base):
    """资料类型字典表"""
    __tablename__ = "material_type_dict"
    
    id = Column(Integer, primary_key=True, autoincrement=True, comment="资料类型ID")
    name = Column(String(50), nullable=False, comment="类型名称")
    
    # 关联关系
    materials = relationship("Material", back_populates="material_type_rel")
    
    def to_dict(self, exclude=None):
        """重写to_dict方法，格式化时间字段"""
        if exclude is None:
            exclude = []
            
        result = {
            column.name: getattr(self, column.name)
            for column in self.__table__.columns
            if column.name not in exclude
        }
        
        # 格式化时间字段
        if hasattr(self, 'create_time') and self.create_time:
            result['create_time'] = self.create_time.strftime("%Y-%m-%d %H:%M:%S")
        if hasattr(self, 'updated_time') and self.updated_time:
            result['updated_time'] = self.updated_time.strftime("%Y-%m-%d %H:%M:%S")
            
        return result


class FileSourceDict(BaseDatabaseModel, Base):
    """文件来源字典表"""
    __tablename__ = "file_source_dict"
    
    id = Column(Integer, primary_key=True, autoincrement=True, comment="来源ID")
    name = Column(String(50), nullable=False, comment="来源名称")
    
    # 关联关系
    materials = relationship("Material", back_populates="file_source_rel")
    
    def to_dict(self, exclude=None):
        """重写to_dict方法，格式化时间字段"""
        if exclude is None:
            exclude = []
            
        result = {
            column.name: getattr(self, column.name)
            for column in self.__table__.columns
            if column.name not in exclude
        }
        
        # 格式化时间字段
        if hasattr(self, 'create_time') and self.create_time:
            result['create_time'] = self.create_time.strftime("%Y-%m-%d %H:%M:%S")
        if hasattr(self, 'updated_time') and self.updated_time:
            result['updated_time'] = self.updated_time.strftime("%Y-%m-%d %H:%M:%S")
            
        return result


class Material(BaseDatabaseModel, Base):
    """资料表"""
    __tablename__ = "material"
    
    id = Column(BigInteger, primary_key=True, autoincrement=True, comment="主键")
    file_topic = Column(String(255), nullable=False, comment="资料主题")
    file_name = Column(String(255), nullable=False, comment="资料名称（含后缀）")
    company = Column(String(255), comment="企业名称")
    file_path = Column(String(500), nullable=False, comment="存储路径（minio）")
    file_type = Column(String(50), nullable=False, comment="文件类型（及通用的文件名称，如xlsx等）")
    material_type = Column(Integer, ForeignKey("material_type_dict.id"), nullable=False, comment="资料类型")
    file_size = Column(BigInteger, default=0, comment="文件大小（字节）")
    duration = Column(Integer, default=0, comment="视频时长（分钟，非视频为0）")
    is_deleted = Column(Boolean, default=False, comment="逻辑删除标记（0-正常，1-删除）")
    file_source = Column(Integer, ForeignKey("file_source_dict.id"), comment="文件来源")
    file_hash = Column(String(64), nullable=False, unique=True, comment="文件哈希（SHA256）")
    
    # 关联关系
    material_type_rel = relationship("MaterialTypeDict", back_populates="materials")
    file_source_rel = relationship("FileSourceDict", back_populates="materials")
    
    def to_dict(self, exclude=None):
        """重写to_dict方法，格式化时间字段"""
        if exclude is None:
            exclude = []
            
        result = {
            column.name: getattr(self, column.name)
            for column in self.__table__.columns
            if column.name not in exclude
        }
        
        # 格式化时间字段
        if hasattr(self, 'create_time') and self.create_time:
            result['create_time'] = self.create_time.strftime("%Y-%m-%d %H:%M:%S")
        if hasattr(self, 'updated_time') and self.updated_time:
            result['updated_time'] = self.updated_time.strftime("%Y-%m-%d %H:%M:%S")
            
        return result
